package cn.yeyiu.netonlinevideo.parser.video;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.yeyiu.netonlinevideo.bean.SourceData;
import cn.yeyiu.netonlinevideo.parser.Parser;
import cn.yeyiu.netonlinevideo.viewmodel.DataListViewModel;
import cn.yeyiu.util.NetUtil;
import cn.yeyiu.util.bean.MediaData;
import cn.yeyiu.util.bean.VideoInfo;

public class XiaoPigParser extends Parser {
    public XiaoPigParser(SourceData source) {
        super(source);
    }

    @Override
    public Object getBaseData(String type, int pageIndex) {
        //GET https://api.pv123.app/v1/groups/11/videos?lower=0&upper=9&status=valid&sort_type=comprehensive
        String vtype = getArgv(type, "vtype");
        int lower = pageIndex * source.pageSize;
        int upper = lower + source.pageSize - 1;
        String url = source.url + "/%s/videos?lower=%d&upper=%d&status=valid&sort_type=comprehensive";
        url = String.format(url, vtype, lower, upper);
        String html = NetUtil.getByUrl(url, new HashMap<String, String>() {{
            put("Origin", "https://api.pv123.app");
        }});
        return JSONObject.parseObject(html);
    }

    @Override
    public List<MediaData> getDataList(Object data, String type) {
        JSONObject jo = (JSONObject) data;
        JSONArray array = jo.getJSONArray("videos");

        List<MediaData> videoInfos = new ArrayList<>();
        MediaData mediaData;
        VideoInfo videoInfo;
        for (int i = 0; i < array.size(); ++i) {
            JSONObject ob = array.getJSONObject(i);
            videoInfo = new VideoInfo();
            mediaData = new MediaData();

            videoInfo.code = source.code;
            videoInfo.type = type;
            videoInfo.title = ob.getString("title");
            String pic_url = ob.getJSONArray("encodingThumbnails").getJSONObject(0).getString("data_url");
            getPicContent(videoInfo, pic_url);
            videoInfo.videoSrc = "https://pv-oa-huawei.jijiyiyiwealth.com" + ob.getString("uploadedPath");
            videoInfo.info = "{'Origin': 'https://api.pv123.app','Referer': 'https://api.pv123.app'}";

            mediaData.wrap(videoInfo);
            videoInfos.add(mediaData);
        }
        return videoInfos;
    }

    void getPicContent(VideoInfo videoInfo, String pic_url) {
        videoInfo.picSrc = NetUtil.getByUrl("https://pv-oa-huawei.jijiyiyiwealth.com" + pic_url,
                new HashMap<String, String>() {{
                    put("Origin", "https://api.pv123.app");
                    put("Referer", "https://api.pv123.app");
                }}
        );
    }
}
